package lab5task3;

import java.util.concurrent.TimeoutException;

/**
 * 
 * Main class of database connection pool implementation 
 * 
 * @author Bulaev Igor
 *
 */

public class Main {

	private ConnectionPool pool;

	public static void main(String[] args) {
		new Main().init();
	}

	private void init() {
		pool = new ConnectionPool("url", "user", "pass", 10);
		for (int i = 0; i < 10; i++) {
			new Thread(new WorkerRunnable()).start();
		}
	}

	/**
	 * 
	 * Worker runnable for testing purposes
	 * 
	 * @author Bulaev Igor
	 *
	 */
	
	private class WorkerRunnable implements Runnable {

		Connection conn;

		@Override
		public void run() {
			while (true) {
				long seed = (long) (Math.random() * 1500);
				if (conn == null || conn.getOwner() == null || conn.getOwner() != Thread.currentThread()) {
					try {
						conn = pool.checkOut();
					} catch (InterruptedException ie) {
						ie.printStackTrace();
					} catch (TimeoutException te) {
						te.printStackTrace();
					}
				} else if (seed % 5 == 0) {
					try{
						pool.checkIn(conn);
					} catch(ConnectionClosedException cce) {
						cce.printStackTrace();
					}
				} else if (seed % 5 == 1) {
					try {
						conn.simulateWork();
					} catch (ConnectionClosedException cce) {
						cce.printStackTrace();
					}
				}
				try {
					Thread.sleep(seed);
				} catch (InterruptedException ie) {
					ie.printStackTrace();
				}
			}
		}
	}

}
